﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Annual_faculty_promotions.Data;
using Annual_faculty_promotions.Service.Contracts;
using Annual_faculty_promotions.WebUI.Helpers.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Annual_faculty_promotions.WebUI.Areas.UserArea.Controllers
{
    public class UserAdminController : Controller
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IApplicationRoleManager _roleManager;
        private readonly IApplicationUserManager _userManager;
        private readonly IUserService _userService;
        public UserAdminController(IUnitOfWork unitOfWork, IApplicationUserManager userManager,
                                    IApplicationRoleManager roleManager,
                                    IUserService userService)
        {
            _unitOfWork = unitOfWork;
            _userManager = userManager;
            _roleManager = roleManager;
            _userService = userService;
        }


        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [AjaxOnly]
        public ActionResult SetRole(int uid)
        {
            var data = (from u in _userService.Where(x => x.Id == uid)
                        select new
                        {
                            User = u,
                            User_Roles = u.Roles,
                            User_Roles_Department = u.Roles.Select(c => new { c.Department })
                        });

            var model = data.AsEnumerable().Select(m => m.User).FirstOrDefault();

            if (model == null)
                return new HttpNotFoundResult();
            return PartialView("_SetRole", model);
        }
        public ActionResult GetUsers()
        {
            //var users = _userService.Where(u => u.EmailConfirmed == true && u.Profile != null).Include(u => u.Profile).ToList();
            string rolesName = string.Empty;
            var data = (from u in _userService.Where(u => u.EmailConfirmed == true && u.Profile != null)
                        select new
                        {
                            User = u,
                            User_Roles = u.Roles,
                            User_Roles_Department = u.Roles.Select(c => new { c.Department }),
                            User_Profile = u.Profile
                        });

            var users = data.AsEnumerable().Select(c => c.User).ToList();
            var roles = _roleManager.GetAllCustomRolesAsQueryable().ToList();

            JArray ja = new JArray();
            if (users != null)
            {
                foreach (var item in users)
                {
                    var itemObject = new JObject
                {
                    {"id",item.Id},
                    {"text", item.Profile.Name + " " +item.Profile.Family},
                    {"email",item.Email},
                    {"avatar",item.Profile.Avatar},
                    {"departmentId",item.Roles.Any() ? item.Roles.FirstOrDefault().Department.Name : ""}                    
                };
                    rolesName = item.Roles.Aggregate(rolesName, (current, itm) => current + (roles.Find(c => c.Id == itm.RoleId).PersianName + " ، "));
                    itemObject.Add("roleName", rolesName);
                    ja.Add(itemObject);
                    rolesName = string.Empty;
                }
            }
            JObject jo = new JObject();
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }


        public ActionResult GetUserRole(int uid)
        {
            var userRole = _roleManager.GetAllCustomUserRole().Where(x => x.UserId == uid).Include(x => x.Department);
            var roles = _roleManager.GetAllCustomRolesAsQueryable().ToList();
            JArray ja = new JArray();
            if (userRole != null)
            {
                foreach (var item in userRole)
                {
                    var itemObject = new JObject
                    {                   
                        {"RoleId", item.RoleId},
                        {"DepartmentId",item.Department.Id},
                        {"DepartmentName",item.Department.Name}
                    };
                    foreach (var itm in roles)
                    {
                        if (item.RoleId == itm.Id)
                        {
                            itemObject.Add("RoleName", itm.Name);
                            itemObject.Add("RolePersianName", itm.PersianName);
                        }

                    }
                    ja.Add(itemObject);
                }
            }
            JObject jo = new JObject();
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult DestroyUserRole(int userId, int roleId, int departmentId)
        {

            try
            {
                _userService.DeleteUserRole(userId, roleId, departmentId);
                _unitOfWork.SaveChanges();
                return Json(new { success = true, Msg = "حذف شد" });
            }
            catch (Exception)
            {

                return Json(new { success = false, Msg = "حذف نشد" });
            }
        }

        public ActionResult GetRoleByUserId(int userId)
        {
            var roles = _roleManager.FindUserRoles(userId);

            JArray ja = new JArray();
            if (roles != null)
            {
                foreach (var item in roles)
                {
                    var itemObject = new JObject
                {
                    {"id",item.Id},
                    {"text", item.Name}
                };
                    ja.Add(itemObject);
                }
            }
            JObject jo = new JObject();
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }


        public ActionResult GetRoles()
        {
            var roles = _roleManager.GetAllCustomRolesAsQueryable().ToList();

            JArray ja = new JArray();
            if (roles != null)
            {
                foreach (var item in roles)
                {
                    var itemObject = new JObject
                {
                    {"id",item.Id},
                    {"text", item.PersianName},
                    {"Name", item.Name}
                };
                    ja.Add(itemObject);
                }
            }
            JObject jo = new JObject();
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(ja), "application/json");
        }

        public async Task<ActionResult> DestroyUserRole(int userid, string rolename)
        {
            await _userManager.RemoveFromRoleAsync(userid, rolename);
            return Json(new { success = true, Msg = "عملیات موفق آمیز بود" });
        }



        [HttpPost]
        public ActionResult CreateUserRole(int userid, int roleId, int structId)
        {

            var result = _roleManager.AddUserRole(userid, roleId, structId);
            if (!result)
            {
                return Json(new { success = true, Msg = "خطا در عملیات" });
            }
            return Json(new { success = true, Msg = "عملیات موفق آمیز بود" });


            // return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
    }
}